<template>
  <div class="login-page">
    <div class="login-container">
      <h1 class="title">家庭医生后台管理端</h1>
      <p class="subtitle">
        {{ formType === 'login' ? '欢迎回来，请登录您的账户' : '创建新账户' }}
      </p>

      <div class="tab-container">
        <div
            class="tab-item"
            :class="{ 'active': formType === 'login' }"
            @click="formType = 'login'"
        >
          登录
        </div>
        <div
            class="tab-item"
            :class="{ 'active': formType === 'register' }"
            @click="formType = 'register'"
        >
          注册
        </div>
      </div>

      <form @submit.prevent="submitForm">
        <div class="input-group">
          <input
              type="text"
              class="input-field"
              placeholder="手机号"
              maxlength="11"
              v-model="phone"
          />
        </div>

        <div class="input-group code-group" v-if="formType === 'register'">
          <input
              type="text"
              class="input-field"
              placeholder="验证码"
              v-model="verificationCode"
          />
          <button
              type="button"
              class="code-btn"
              @click="getVerificationCode"
              :disabled="isCountingDown"
          >
            {{ isCountingDown ? `${countdown}s 后重试` : '获取验证码' }}
          </button>
        </div>

        <div class="input-group">
          <input
              type="password"
              class="input-field"
              placeholder="密码"
              v-model="password"
          />
        </div>

        <div class="input-group" v-if="formType === 'register'">
          <input
              type="password"
              class="input-field"
              placeholder="确认密码"
              v-model="confirmPassword"
          />
        </div>

        <!-- 新增：角色选择 -->
        <div class="input-group" v-if="formType === 'register'">
          <select class="input-field" v-model="roleId">
            <option :value="null" disabled>请选择注册角色</option>
            <option v-for="role in roles" :key="role.id" :value="role.id">
              {{ role.name }}
            </option>
          </select>
        </div>

        <button type="submit" class="submit-btn">
          {{ formType === 'login' ? '登 录' : '立即注册' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script>
import { Login, register, sendCode } from "../api/user.js";
import {useUserStore} from "../store/user.js";

export default {
  name: "LoginPage",
  data() {
    return {
      formType: 'login',
      phone: "15855383771",
      password: "123456",
      confirmPassword: "",
      verificationCode: "",
      roleId: null, // 新增：用于绑定角色选择
      roles: [ // 新增：角色列表 (注意：ID需要与后端对应)
        { id: 1, name: '管理员' },
        { id: 2, name: '医护' },
        { id: 3, name: '医生' }
      ],
      isCountingDown: false,
      countdown: 60,
      timer: null,
    };
  },
  methods: {
    submitForm() {
      if (this.formType === 'login') {
        this.handleLogin();
      } else {
        this.handleRegister();
      }
    },

    async getVerificationCode() {
      if (!this.phone) {
        this.$message.error("请先输入手机号");
        return;
      }
      try {
        await sendCode(this.phone);
        this.$message.success("验证码已发送");
        this.isCountingDown = true;
        this.timer = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown--;
          } else {
            clearInterval(this.timer);
            this.isCountingDown = false;
            this.countdown = 60;
          }
        }, 1000);
      } catch (error) {
        this.$message.error("验证码发送失败，请稍后再试");
      }
    },

    async handleLogin() {
      if (!this.phone || !this.password) {
        this.$message.error("手机号和密码不能为空");
        return;
      }
      try {
        let { data: data } = await Login({ phone: this.phone, password: this.password });
        console.log(data);
        useUserStore().loginSuccess(data.data.user);
        if (data.code === 200) {
          this.$message.success("登录成功");
          sessionStorage.setItem("token", data.data.token);
          this.$router.push("/home");
        } else {
          this.$message.error(data.msg || '登录失败');
        }
      } catch (error) {
        this.$message.error('登录请求失败，请检查网络');
      }
    },

    async handleRegister() {
      // 1. 前端校验
      if (!this.phone || !this.password || !this.verificationCode || !this.roleId) {
        this.$message.error("所有字段均为必填项");
        return;
      }
      if (this.password !== this.confirmPassword) {
        this.password = ''
        this.confirmPassword = ''
        this.$message.error("两次输入的密码不一致");
        return;
      }

      // 2. 调用注册接口
      try {
        const { data: data } = await register({
          phone: this.phone,
          password: this.password,
          code: this.verificationCode,
          roleId: this.roleId
        });

        if (data.code === 200) {
          this.$message.success("注册成功！请登录。");
          // 切换到登录页
          this.formType = 'login';
        } else {
          this.$message.error(data.msg || '注册失败');
        }
      } catch (error) {
        this.$message.error('注册请求失败，请检查网络');
      }
    }
  },
  beforeDestroy() {
    // 组件销毁前清除计时器，防止内存泄漏
    clearInterval(this.timer);
  }
}
</script>

<style scoped>
/* ... 样式保持不变 ... */
.login-page {
  width: 100vw;
  height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
  "Helvetica Neue", Arial, sans-serif;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  width: 400px;
  padding: 40px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 16px;
  color: #888;
  margin-bottom: 30px;
}

.tab-container {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
}
.tab-item {
  font-size: 18px;
  color: #888;
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
}
.tab-item.active {
  color: #4c83ff;
  font-weight: bold;
  border-bottom-color: #4c83ff;
}


.input-group {
  margin-bottom: 20px;
}

/* 新增：验证码容器样式 */
.code-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-field {
  width: 100%;
  height: 50px;
  padding: 0 20px;
  box-sizing: border-box;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 25px;
  transition: border-color 0.3s;
}

.input-field:focus {
  border-color: #4c83ff;
  outline: none;
}

/* 新增：获取验证码按钮样式 */
.code-btn {
  height: 50px;
  padding: 0 20px;
  border-radius: 25px;
  border: 1px solid #ddd;
  background-color: #f5f5f5;
  color: #555;
  cursor: pointer;
  white-space: nowrap; /* 防止文字换行 */
  transition: all 0.3s;
}
.code-btn:hover {
  border-color: #4c83ff;
  color: #4c83ff;
}
/* 倒计时状态下的禁用样式 */
.code-btn:disabled {
  background-color: #eee;
  color: #aaa;
  cursor: not-allowed;
  border-color: #ddd;
}


.submit-btn {
  width: 100%;
  height: 50px;
  border: none;
  border-radius: 25px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.1s;
  background-color: #4c83ff;
  color: white;
  margin-top: 10px;
}
.submit-btn:hover {
  background-color: #2d67f8;
}
.submit-btn:active {
  transform: scale(0.98);
}
</style>

